package com.openbrew.openbrewpos;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import utils.URLTools;


import Models.POSDiscount;
import Models.POSLineItems;
import Models.POSSale;
import Presenter.POSSalePresenter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.PopupMenu.OnMenuItemClickListener;

public class POSView extends Activity {
	//Define class variables
	public ProgressDialog modalDialog = null;
	public ArrayList<POSSale> openTabs = null;
	public ArrayList<POSLineItems> lineItems = null;
	
	//Place holders for views and components
	private ListView tabListView;
	private ListView lineItemListView;
	private TextView tabName;
	
	//Needed for popupMenu
	private PopupMenu popupMenu;
	private final static int ONE = 1;
	private final static int TWO = 2;
	private final static int THREE = 3;
	private final static int FOUR = 4;
	
	//indexes for arrays.
	private int selectedTabItemIdx = 0;
	private int selectedTabIdx = 0;
	
	//Constant for new tab on list
	private final static String NOTAB = "Walk Up";

	//Create frame
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_posview);
		//Initializations
		initializeComponents();
		initializePopupMenu();
		//Load listeners
		setPopupMenuListner();
		addListenerOnTabList();
		setLineItemListListener();
		//Load class arrays
		loadLists();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.posview, menu);
		return true;
	}
	
	/**********************************************************************************************
	 * Setup code.
	 **********************************************************************************************/
	private void initializeComponents(){
		tabListView = (ListView) findViewById(R.id.listView_open_tabs);
		lineItemListView = (ListView) findViewById(R.id.listView_tabItems);
		tabName = (TextView) findViewById(R.id.txtView_pos_tabName);
	}
	
	private void initializePopupMenu(){
		popupMenu = new PopupMenu(this, findViewById(R.id.listView_tabItems));
        popupMenu.getMenu().add(Menu.NONE, ONE, Menu.NONE, "Change Quantity");
        popupMenu.getMenu().add(Menu.NONE, TWO, Menu.NONE, "Change Discount");
        popupMenu.getMenu().add(Menu.NONE, THREE, Menu.NONE, "Remove Item From List");
        popupMenu.getMenu().add(Menu.NONE, FOUR, Menu.NONE, "Override Price");
	}
	
	private void setPopupMenuListner(){
		popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item){
				switch(item.getItemId()){
				case ONE:
					//getAndUpdateCost();
					break;
				case TWO:
					//removePSTFromProduct();
					break;
				case THREE:
					//removePSTFromProduct();
					break;
				case FOUR:
					//removePSTFromProduct();
					break;
				}
				return false;
			}
		});
	}
	
	private void addListenerOnTabList(){
		tabListView.setOnItemClickListener(new OnItemClickListener(){
			@Override
		    public void onItemClick(AdapterView<?> parentView, View selectedItemView, int position, long id) {
				final String selection = (String) parentView.getItemAtPosition(position);
				POSSale sale = getSaleFromCache(selection);
				setSaleDisplayData(sale);
		    }
		});
	}
	
	private void setLineItemListListener(){
		lineItemListView.setOnItemLongClickListener(new OnItemLongClickListener(){
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
				selectedTabItemIdx = pos;
                popupMenu.show();
                return true;
            }
		});
	}
	
	/**********************************************************************************************
	 * Code to load class arrays
	 **********************************************************************************************/
	private void loadLists(){
		//Load all openTabs
		getAllOpenTabs();
	}
	
	private void getAllOpenTabs(){
		modalDialog = ProgressDialog.show(this, null, "Loading Open Tabs...");
		final String strStart = URLTools.getURLString();
		final String str = "possale/runNamedQuery/POSSale.findOpenItems";
		new DownloadAllOpenTabsTask().execute(strStart+str, URLTools.getUSERString(), URLTools.getPASSString());
	}
	
	/**********************************************************************************************
	 * Async Classes for RESTFul Connection
	 **********************************************************************************************/
	private class DownloadAllOpenTabsTask extends AsyncTask<String, Void, String> {
    	@Override
        protected String doInBackground(String... urls) {

            try {
                return RESTfulConnect.getResource(urls[0], urls[1], urls[2]);
            } catch (IOException e) {
            	e.printStackTrace();
            	return "Connection Error";
            }
        }
    	@Override
        protected void onPostExecute(String result) {
    		POSSalePresenter salePresenter = new POSSalePresenter();
    		openTabs = salePresenter.tryJSONParseArray(result);
    		modalDialog.dismiss();
    		//Display the default view.
    		loadInitialView();
        }
    }
	
	/**********************************************************************************************
	 * Functions to display data on the screen.
	 **********************************************************************************************/
	private void loadInitialView(){
		displayOpenTabsToList();
		displayAndHighlightNoTab();
	}
	
	private void displayOpenTabsToList(){
		List<String> list = new ArrayList<String>();
		list.add(NOTAB);
		for(final POSSale tab : openTabs){
			if(!tab.isSaleComplete()){
				list.add(tab.getDisplayString());
			}
		}
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_activated_1, list);
		tabListView.setAdapter(dataAdapter);
	}
	
	private void displayAndHighlightNoTab(){
		if(tabListView.getCount()!=0){
			final String selection = (String) tabListView.getItemAtPosition(0);
			tabListView.setChoiceMode(1);
			tabListView.setItemChecked(0, true);
			POSSale sale = getSaleFromCache(selection);
			setSaleDisplayData(sale);
		}
	}
	
	private POSSale getSaleFromCache(final String s){
		if(s.isEmpty()){
			return null;
		}
		int idx = 0;
		for(final POSSale sale : openTabs){
			if(sale.getDisplayString().equals(s)){
				selectedTabItemIdx = idx;
				return sale;
			}
			idx++;
		}
		return null;
	}
	
	private void setSaleDisplayData(final POSSale sale){
		if(sale != null){
			tabName.setText(sale.getDescription());
			if(sale.getLineItems() != null){
				lineItems = (ArrayList<POSLineItems>) sale.getLineItems();
				ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
				int item = 1;
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("item", "#:");
				map.put("desc", "Description:");
				map.put("qty", "Qty:");
				map.put("disc", "Discount:");
				map.put("subTot", "Cost:");
				list.add(map);
				double grandTotal = 0;
				for(final POSLineItems lineItem : lineItems){
					map = new HashMap<String, String>();
					map.put("item", Integer.toString(item));
					double cost = 0;
					int qty = 0;
					double subTotal = 0;
					if(lineItem.getProduct() != null){
						map.put("desc", lineItem.getProduct().getBeer().getName() + " - " + lineItem.getProduct().getPSTString());
						cost = lineItem.getProduct().getCost();
						qty = lineItem.getQty();
					} else {
						map.put("desc", lineItem.getSupply().getSupplyName());
						cost = lineItem.getSupply().getResalePrice();
						qty = lineItem.getQty();
					}
					map.put("qty", Integer.toString(qty));
					if(lineItem.getDiscount()!=null){
						map.put("disc", lineItem.getDiscount().getDescription());
					} else {
						map.put("disc", "none");
					}
					if(lineItem.getProduct() != null){
						if(lineItem.getDiscount().getFlatRate()>0){
							subTotal = ((cost * qty) - (lineItem.getDiscount().getFlatRate() * qty));
						} else {
							subTotal = ((cost*qty) - (cost * qty * (lineItem.getDiscount().getPctRate()/100)));
						}
					} else {
						subTotal = cost * qty;
					}
					map.put("subTot", "$"+String.format("%.2f", subTotal));
					list.add(map);
					grandTotal += subTotal;
					item++;
				}
				map = new HashMap<String, String>();
				map.put("item", "");
				map.put("desc", "");
				map.put("qty", "");
				map.put("disc", "Grand Total:");
				map.put("subTot", "$"+String.format("%.2f", grandTotal));
				list.add(map);
				
				SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.list_row_layout,
						new String[]{"item", "desc", "qty", "disc", "subTot"}, new int[] {R.id.ITEM_CELL, R.id.DESC_CELL, R.id.QTY_CELL, R.id.DISC_CELL, R.id.SUBTOT_CELL});
				lineItemListView.setAdapter(adapter);
			} else {
				lineItems = new ArrayList<POSLineItems>();
				List<String> list = new ArrayList<String>();
				ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
						android.R.layout.simple_list_item_1, list);
				lineItemListView.setAdapter(dataAdapter);
			}
		} else {
			tabName.setText(NOTAB);
			lineItems = new ArrayList<POSLineItems>();
			List<String> list = new ArrayList<String>();
			ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, list);
			lineItemListView.setAdapter(dataAdapter);
		}
	}
}
